﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace spilverlight.webparts
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:spilverlight runat=server></{0}:spilverlight>")]
    public class spilverlight : WebPart, INamingContainer
    {
        [WebBrowsable(true)]
        [Category("Spilverlight Config")]
        [Personalizable(PersonalizationScope.Shared)]
        [System.Web.UI.WebControls.WebParts.WebDisplayName("Path to XAP file")]
        public string XAPFilePath { get; set; }

        [WebBrowsable(true)]
        [Category("Spilverlight Config")]
        [Personalizable(PersonalizationScope.Shared)]
        [System.Web.UI.WebControls.WebParts.WebDisplayName("Height")]
        public string SLHeight { get; set; }

        [WebBrowsable(true)]
        [Category("Spilverlight Config")]
        [Personalizable(PersonalizationScope.Shared)]
        [System.Web.UI.WebControls.WebParts.WebDisplayName("Width")]
        public string SLWidth { get; set; }

        [WebBrowsable(true)]
        [Category("Spilverlight Config")]
        [Personalizable(PersonalizationScope.Shared)]
        [System.Web.UI.WebControls.WebParts.WebDisplayName("Init Properties")]
        public string InitProps { get; set; }

        public spilverlight()
        {
            this.XAPFilePath = string.Empty;
            this.SLHeight = "200";
            this.SLWidth = "200";
            this.InitProps = string.Empty;
        }

        protected override void CreateChildControls()
        {
            string SLPath = Page.ClientScript.GetWebResourceUrl(this.GetType(), "spilverlight.webresources.Silverlight.js");
            string SLHelper = Page.ClientScript.GetWebResourceUrl(this.GetType(), "spilverlight.webresources.SilverlightHelper.js");
            Page.ClientScript.RegisterClientScriptInclude("spilverlight.webresources.Silverlight.js", SLPath);
            Page.ClientScript.RegisterClientScriptInclude("spilverlight.webresources.SilverlightHelper.js", SLHelper);

        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            string hostID = "slHost_" + this.ID;
            string callSL = "<div id=\"" + hostID + "\"></div>";
            string initProps = (this.InitProps == string.Empty)?"null":this.InitProps;
            string slScript = "<script>createSL('" + hostID + "', '" + this.SLWidth + "', '" + this.SLHeight + "', '" + this.XAPFilePath + "', '" + initProps + "');</script>";

            if (XAPFilePath != string.Empty)
            {
                writer.Write(callSL);
                Page.ClientScript.RegisterStartupScript(this.GetType(), hostID, slScript);
            }
        }
    }
}
